package engine.systems.spatial.path
{
	import engine.classes.enumerations.SystemPriority;
	import engine.groups.Group;
	import engine.systems.update.GameSystem;
	import engine.utils.GeomUtils;
	
	import flash.geom.Point;
	
	public class PathSystem extends GameSystem
	{
		private var point:Point;
		private var distance:Number;
		
		public function PathSystem()
		{
			super(PathNode, updateNode);
			
			this.priority = SystemPriority.PRE_MOTION;
		}
		
		private function updateNode(node:PathNode, time:Number):void
		{
			if(!node.path.active) return;
			
			if(node.path.invalidate)
			{
				node.path.invalidate = false;
				
				point = node.path.points[node.path.index];
				node.target.spatial.x = point.x;
				node.target.spatial.y = point.y;
			}
			
			distance = GeomUtils.distance(node.spatial.x, node.spatial.y, node.target.spatial.x, node.target.spatial.y);
			
			if(distance < node.target.threshold)
			{
				node.path.forward ? node.path.index++ : node.path.index--;
				
				point = node.path.points[node.path.index];
				node.target.spatial.x = point.x;
				node.target.spatial.y = point.y;
				
				if(!node.path.active) node.path.complete.dispatch(node.entity);
			}
		}
	}
}